import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select, Tree, TreeSelect } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import { getNewTreeData, findRowData, addRowData, removeRowData, confirmDelete } from 'lib/fun'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
const SelectTreeNode = TreeSelect.TreeNode;

class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      editType: "",
      rowdata: {},
      treeData: [],
      selected: {},
      search: {},
      current: 1,   //当前第几页
      total: 10,   //总共多少页
      pageSize: 10   //每页多少行
    }
  }

  componentDidMount() {
    this.onLoadData();
  }

  componentWillReceiveProps(nextProps){
    var self = this;
    console.log(nextProps.search, this.props.search);
    // if(!_.isEqual(this.props.search, nextProps.search)){
    //   this.search = nextProps.search;
    //   self.onLoadData();
    // }
  }

  onSelect = (info, e) => {
    console.log(info);
    var selected = findRowData(this.state.treeData, info);

    // this.props.addressChange(selected);
    if(selected){
      this.setState({
        selected
      });
    }

    // e.node.onExpand();
    this.onLoadData(e.node);
  }

  getAreaLevel = (code)=>{
    return _.result(_.find(this.props.config.areaLevel||[], function(chr) {
      return chr.dictionaryCode == code;
    }), 'dictionaryName');
  }

  onLoadData = (treeNode) => {
    var self = this;
    console.log('load area2');
    var selected = findRowData(this.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        self.setState({
          loading: false
        });
        resolve();
      }else{
        var { areaLevelId, areaCode, areaName, areaParentCode } = this.props.search;
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            // areaLevelId,
            // areaCode, 
            // areaName, 
            // areaParentCode,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list
            }
            self.setState({
              loading: false,
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  pageOnChange = (page)=>{
    this.setState({
      current: page
    });
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(this.state.current*this.state.pageSize/pageSize);
    var pageSize = pageSize;
    var current = page;
    this.setState({
      pageSize,
      current
    });
  }
  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      if(this.state.selected.areaCode){
        this.setState({
          visible: true,
          editType: 'new'
        });
      }else{
        message.error('请先选择区划！');
      }
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = findRowData(this.state.treeData, rowdata.areaId);
      if(find){
        if(find.areaParentId != rowdata.areaParentId){
          removeRowData(self.state.treeData, rowdata.areaId);
          addRowData(self.state.treeData, rowdata);
        }else{
          Object.assign(find, {
            areaCode: rowdata.areaCode,
            areaName: rowdata.areaName,
            areaNameZw: rowdata.areaNameZw,
            areaLevelCode: rowdata.areaLevelCode,
            areaParentId: rowdata.areaParentId,
            areaParentCode: rowdata.areaParentCode,
            areaTypeCode: rowdata.areaTypeCode,
            remark: rowdata.remark
          });
        }
      }
      self.setState({
        visible: false,
        rowdata: {},
        treeData: self.state.treeData
      });
      message.success('修改记录成功！');
    }else{
      addRowData(self.state.treeData, rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        treeData: self.state.treeData
      });
      message.success('增加记录成功！');
    }
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/area/delete',
        data: {
          "areaId": id
        },
        success: function(data){
          removeRowData(self.state.treeData, id);
          self.setState({
            treeData: self.state.treeData
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除区划');
    }); 
  }
  
  render() {
    var pagination = {
      current: this.state.current,
      total: this.state.total,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      pageSize: this.state.pageSize,
      onShowSizeChange: this.showSizeChange
    };
    console.log('selected', this.state.selected)
    const columns = [{
        title: '区划代码',
        dataIndex: 'areaCode'
      }, {
        title: '区划名称',
        dataIndex: 'areaName'
      }, {
        title: '行政级别',
        dataIndex: 'areaLevelCode',
        render: (text, record) => <span>{ this.getAreaLevel(record.areaLevelCode)||"-" }</span>
      }, {
        title: '上级区划名称',
        dataIndex: 'areaParentId',
        render: ()=> <span>{ this.state.selected.areaName }</span>
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Dropdown overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={this.operate.bind(this, "edit", record)} href="javascript:;">编辑</a>
                </Menu.Item>
                <Menu.Item>
                  <a href="javascript:;" onClick={this.doDelete.bind(this, record.areaId)}>删除</a>
                </Menu.Item>
              </Menu>
            }>
              <a className="ant-dropdown-link" href="javascript:;">
                操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        )
    }];

    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <TreeNode title={item.areaName} key={item.areaId}>{loop(item.children)}</TreeNode>;
      }
      return <TreeNode title={item.areaName} key={item.areaId} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);

    const areaLevel = this.props.config.areaLevel||[];
    const areaType = this.props.config.areaType||[];

    var dataList = this.state.selected.children||this.state.treeData||[];
    var { areaCode, areaName } = this.props.search;
    if(areaCode){
      dataList = _.filter(dataList, _.negate((item)=>{
        return item.areaCode != areaCode
      }))
    }
    if(areaName){
      dataList = _.filter(dataList, _.negate((item)=>{
        return item.areaName != areaName
      }))
    }
    
    return (
    	<div>
        <Row>
          <Col span={4}>
            <Tree 
              ref="tree"
              autoExpandParent
              onSelect={this.onSelect} 
              loadData={this.onLoadData}
            >
              {treeNodes}
            </Tree>
          </Col>
          <Col span={20}>
            <div className="table-con no-expand">
              <Table
                columns={ columns }
                dataSource={ dataList }
                pagination={ false }
                loading={this.state.loading}
                rowKey="areaId"
                title={() => (<div>
                                <Button type="primary" style={{marginRight: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建</Button>
                                {/*<Button type="primary" icon="export">批量导入</Button>*/}
                              </div>)}
              />
            </div>
          </Col>
        </Row>
        <EditModule 
          visible={ this.state.visible }
          address={ this.state.selected }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
          areaLevel={ areaLevel }
          areaType={ areaType }
        />
    	</div>
    )
  }
}

module.exports = ModuleName


class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      treeData: []
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
    }
    if(nextProps.visible&&nextProps.type=='edit'&&this.state.treeData.length <= 0){
      this.loadArea();
    }
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(this.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleCommit = () => {
    var self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { type, rowdata, address  } = self.props;
        console.log(values);
        if(self.props.type == 'edit'){
          values.areaId = rowdata.areaId;
          values.areaParentId = values.areaParentCode;
        }else{
          values.areaParentId = address.areaId;
          values.areaParentCode = address.areaCode;
        }
        Ajax({
          url: '/area/save',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type, data);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const { visible, type, rowdata, address, areaType, areaLevel } = this.props;
    
    console.log(this.state.treeData);
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    return (<Modal 
              title={ type == 'edit'?"修改区划划分":"新建区划划分" }
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="区划代码">
                        {getFieldDecorator("areaCode",{
                          initialValue: type == 'edit'?rowdata.areaCode:"",
                          rules: [{
                            required: true, message: '请输入区划代码',
                          }]
                        })(
                          type == 'edit'?<Input disabled/>:<Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="区划名称">
                        {getFieldDecorator("areaName",{
                          initialValue: type == 'edit'?rowdata.areaName:"",
                          rules: [{
                            required: true, message: '请输入区划名称',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="区划名称(藏)">
                        {getFieldDecorator("areaNameZw",{
                          initialValue: type == 'edit'?rowdata.areaNameZw:"",
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="行政区划级别">
                        {getFieldDecorator("areaLevelCode",{
                          initialValue: type == 'edit'?rowdata.areaLevelCode+"":"",
                          rules: [{
                            required: true, message: '请选择区划级别',
                          }]
                        })(
                          <Select>
                            {
                              areaLevel.map(function(obj){
                                return (<Select.Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Select.Option>)
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="上级区划名称">
                        {getFieldDecorator("areaParentCode",{
                          initialValue: type == 'edit'?rowdata.areaParentId+"":address.areaName,
                          rules: [{
                            required: true, message: '请选择上级区划名称',
                          }]
                        })(
                          type == 'edit'?(
                            <TreeSelect
                              loadData={ this.loadArea }
                            >
                              { treeNodes }
                            </TreeSelect>
                          ):(
                            <Input disabled/>
                          )
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="行政区划类型">
                        {getFieldDecorator("areaTypeCode",{
                          initialValue: type == 'edit'?rowdata.areaTypeCode+"":"",
                          rules: [{
                            required: true, message: '请选择区划类型',
                          }]
                        })(
                          <Select>
                            {
                              areaType.map(function(obj){
                                return (<Select.Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Select.Option>)
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20} className="area-modifier">
                    <Col span={24}>
                      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="概述">
                        {getFieldDecorator("remark",{
                          initialValue: type == 'edit'?rowdata.remark:"",
                        })(
                          <Input type="textarea"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>);
  }
}
var EditModule = Form.create()(Edit);
